<template>
  <div class="app-container">


    <div class="filter-container">
      <el-input v-model="params.name"   placeholder="角色名称" style="width: 200px;" class="filter-item" @keyup.enter.native="fetchData" clearable/>
      <el-input v-model="params.desc"   placeholder="描述" style="width: 200px;margin-left: 20px;" class="filter-item" @keyup.enter.native="fetchData" clearable />
      <el-select v-model="params.status" class="filter-item" style="margin-left: 20px;" placeholder="状态">
        <el-option  key="0" label="启用" :value="0" />
        <el-option  key="1" label="停用" :value="1" />
      </el-select>
      <el-button v-waves class="filter-item input-margin" type="primary" icon="el-icon-search" @click="fetchData">
        搜索
      </el-button>
      <el-button @click="resetForm()"  type="success" icon="el-icon-warning-outline"  class="filter-item">重置</el-button>

    </div>
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="editOrAdd(0)">
        添加
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"

      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="角色名称">
        <template slot-scope="scope">
          {{ scope.row.roleName }}
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center">
        <template slot-scope="scope">
          {{ scope.row.roleIntro }}
        </template>
      </el-table-column>
      <el-table-column label="注册时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.status==0">启用</span>
          <span v-if="scope.row.status==1">停用</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="操作">
        <template slot-scope="scope">
          <el-row>

            <el-button type="text" @click="editOrAdd(1,scope.row)">编辑</el-button>
            <el-button type="text" @click="updateRoleStatus(scope.row.id)" v-if="scope.row.status===1">启用</el-button>
            <el-button type="text" @click="updateRoleStatus(scope.row.id)" v-if="scope.row.status===0">停用</el-button>
            <el-button type="text" @click="deleteUser(scope.row.id)" v-if="scope.row.roleId!=='001'">删除</el-button>

<!--            <el-tooltip class="item" effect="dark" content="编辑" placement="top">-->
<!--              <el-button type="primary" icon="el-icon-edit" circle @click="editOrAdd(1,scope.row)"></el-button>-->
<!--            </el-tooltip>-->
<!--            <el-tooltip class="item" effect="dark" content="启用" placement="top" v-if="scope.row.status===1">-->
<!--              <el-button type="success" icon="el-icon-success" circle @click="updateRoleStatus(scope.row.id)"></el-button>-->
<!--            </el-tooltip>-->
<!--            <el-tooltip class="item" effect="dark" content="停用" placement="top" v-if="scope.row.status===0">-->
<!--              <el-button type="warning" icon="el-icon-error" circle @click="updateRoleStatus(scope.row.id)"></el-button>-->
<!--            </el-tooltip>-->
<!--            <el-tooltip class="item" effect="dark" content="删除" placement="top" v-if="scope.row.roleId!=='001'">-->
<!--              <el-button type="danger" icon="el-icon-delete" circle @click="deleteUser(scope.row.id)"></el-button>-->
<!--            </el-tooltip>-->
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="params.page" :limit.sync="params.pageSize"
                @pagination="fetchData"/>

    <el-dialog :title="dialogTitles[dialogIndex]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="adminData"  label-width="80px"
               style="margin-left:50px;margin-right: 50px">
        <el-form-item label="角色名称" prop="username">
          <el-input v-model="adminData.roleName"/>
        </el-form-item>

        <el-form-item label="描述" prop="realName">
          <el-input v-model="adminData.roleIntro"/>
        </el-form-item>

        <el-tree
          :data="treeList"
          show-checkbox
          node-key="id"
          :default-checked-keys="roleResource"
          :props="defaultProps"  ref="tree">
        </el-tree>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="save">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { authList, treeList,roleResource,roleEdit,updateRoleStatus,delRole } from '@/api/role'
  import Pagination from '@/components/Pagination'
  import waves from '@/directive/waves'

  export default {
    components: { Pagination },
    directives: { waves },
    data() {
      return {
        list: null,
        listLoading: true,
        total: 10,
        dialogTitles: ['添加', '编辑'],
        dialogIndex: 0,
        dialogFormVisible: false,
        adminData: {},
        params: {
          page: 1,
          pageSize: 10
        },
        rules: {
        //  rid: [{ required: true, message: '请选择角色', trigger: 'change' }],
          roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
          roleIntro: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
         // realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }]
        },
       // roleList: [],
        treeList: [],
        roleResource:[],
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      }
    },
    created() {
      this.fetchData()
      //this.initRoles()
    },
    methods: {
      fetchData() {
        this.listLoading = true
        authList(this.params).then(response => {
          this.total = response.total
          this.list = response.rows
          this.listLoading = false
        })
      },
      initTree() {
        treeList().then(res => {
          this.treeList = res
        })
      },
      initRoleResource(roleId){
        roleResource(roleId).then(res=>{
          this.roleResource=res;
        })
      },
      // initRoles() {
      //   roleList().then(res => {
      //     this.roleList = res
      //   })
      // },
      editOrAdd(index, item) {
        this.adminData = Object.assign({}, item)
        this.initTree();
        if (index === 1) {
          //delete this.adminData.createTime
          //delete this.adminData.statusString
          //delete this.ad
          // minData.name

          this.initRoleResource(item.roleId);
        }
        this.dialogIndex = index
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      save() {
        let authority='';
        console.log(this.$refs.tree.getCheckedNodes(false,true))
        this.$refs.tree.getCheckedNodes(false,true).forEach(item=>{
          authority+=item.id+","
        })
        if(!authority){
          this.$message.error('请选择权限');
          return;
        }
        authority=authority.substr(0,authority.length-1);
        this.adminData.authority=authority;
        delete  this.adminData.statusString
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            roleEdit(this.adminData).then(res => {
              this.dialogFormVisible = false
              this.$message({
                type: 'success',
                message: this.dialogTitles[this.dialogIndex] + '成功!'
              })
              this.fetchData()
            })
          }
        })
      },
      deleteUser(id) {

        this.$confirm('删除角色将删除该角色所有账号, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delRole(id).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.fetchData()
          })

        });
      },
      updateRoleStatus(id){
        updateRoleStatus(id).then(res=>{
          this.$message({
            type: 'success',
            message: '成功!'
          })
          this.fetchData();
        });
      },
      resetForm(){
        this.params={
          page:1,
          pageSize:10
        };
        this.$nextTick(()=>{
          this.fetchData();
        })
      }
    }
  }
</script>
